<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

use app\common\service\PriceCache;

/**
 * 价格业务逻辑
 */
class Price extends LogicBase
{
    /**
     * 获取价格历史搜索条件
     */
    public function getPriceHistoryWhere($data = [])
    {
        $where = [];
        
        // 商品ID筛选
        !empty($data['product_id']) && $where['product_id'] = $data['product_id'];
        
        // 价格范围筛选
        if (isset($data['min_price']) && $data['min_price'] !== '') {
            $where['price'] = ['>=', $data['min_price']];
        }
        if (isset($data['max_price']) && $data['max_price'] !== '') {
            if (isset($where['price'])) {
                $where['price'] = ['between', [$data['min_price'], $data['max_price']]];
            } else {
                $where['price'] = ['<=', $data['max_price']];
            }
        }
        
        // 时间范围筛选（使用price_date字段，确保日期格式一致）
        if (!empty($data['start_time'])) {
            $startTime = is_numeric($data['start_time']) ? date('Y-m-d', $data['start_time']) : date('Y-m-d', strtotime($data['start_time']));
            $where['price_date'] = ['>=', $startTime];
        }
        if (!empty($data['end_time'])) {
            $endTime = is_numeric($data['end_time']) ? date('Y-m-d', $data['end_time']) : date('Y-m-d', strtotime($data['end_time']));
            if (isset($where['price_date'])) {
                $where['price_date'] = ['between', [$startTime, $endTime]];
            } else {
                $where['price_date'] = ['<=', $endTime];
            }
        }
        
        // 搜索条件：商品名称
        !empty($data['search_data']) && $where['product_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        // 日期数据筛选（使用price_date字段）
        if (!empty($data['price_date']) && is_string($data['price_date'])) {
            $where['price_date'] = $data['price_date'];
        }
        
        return $where;
    }

    /**
     * 获取价格监控搜索条件
     */
    public function getPriceMonitorWhere($data = [])
    {
        $where = [];
        
        // 商品ID筛选
        !empty($data['product_id']) && $where['product_id'] = $data['product_id'];
        
        // 监控类型筛选
        !empty($data['monitor_type']) && $where['monitor_type'] = $data['monitor_type'];
        
        // 状态筛选
        isset($data['is_enabled']) && $data['is_enabled'] !== '' && $where['is_enabled'] = $data['is_enabled'];
        
        // 阈值范围筛选
        if (isset($data['min_threshold']) && $data['min_threshold'] !== '') {
            $where['threshold'] = ['>=', $data['min_threshold']];
        }
        if (isset($data['max_threshold']) && $data['max_threshold'] !== '') {
            if (isset($where['threshold'])) {
                $where['threshold'] = ['between', [$data['min_threshold'], $data['max_threshold']]];
            } else {
                $where['threshold'] = ['<=', $data['max_threshold']];
            }
        }
        
        // 时间范围筛选（使用price_date字段，确保日期格式一致）
        if (!empty($data['start_time'])) {
            $startTime = is_numeric($data['start_time']) ? date('Y-m-d', $data['start_time']) : date('Y-m-d', strtotime($data['start_time']));
            $where['price_date'] = ['>=', $startTime];
        }
        if (!empty($data['end_time'])) {
            $endTime = is_numeric($data['end_time']) ? date('Y-m-d', $data['end_time']) : date('Y-m-d', strtotime($data['end_time']));
            if (isset($where['price_date'])) {
                $where['price_date'] = ['between', [$startTime, $endTime]];
            } else {
                $where['price_date'] = ['<=', $endTime];
            }
        }
        
        // 搜索条件：商品名称
        !empty($data['search_data']) && $where['product_name'] = ['like', '%' . $data['search_data'] . '%'];
        
        return $where;
    }

    /**
     * 获取价格列表搜索条件（兼容旧方法）
     * @deprecated 请使用 getPriceHistoryWhere() 方法
     */
    public function getWhere($data = [])
    {
        return $this->getPriceHistoryWhere($data);
    }
    
    /**
     * 获取价格列表
     */
    public function getPriceList($where = [], $field = true, $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        // 排除已删除的记录
        $where[DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        try {
            // 对于简单查询尝试缓存（无分页且条件简单）
            if ($paginate === false && is_array($where) && count($where) <= 3) {
                $cacheKey = md5(serialize($where) . $field . $order);
                $cachedList = PriceCache::getCachedPriceList($cacheKey);
                if ($cachedList !== null) {
                    return $cachedList;
                }
                
                $list = $this->modelPriceHistory->getList($where, $field, $order, $paginate);
                
                // 缓存结果（缓存时间较短，5分钟）
                PriceCache::cachePriceList($cacheKey, $list, 300);
                
                return $list;
            }
            
            // 复杂查询或分页查询不缓存
            return $this->modelPriceHistory->getList($where, $field, $order, $paginate);
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取价格列表失败：' . $e->getMessage());
            return $this->modelPriceHistory->getList($where, $field, $order, $paginate);
        }
    }
    
    /**
     * 价格添加
     */
    public function priceAdd($data = [])
    {
        // 验证数据
        $validate_result = $this->validatePrice->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validatePrice->getError()];
        }
        
        $result = $this->modelPriceHistory->setInfo($data);
        
        if ($result) {
            action_log('新增', '价格新增，product_id：' . $data['product_id']);
            
            // 清除相关缓存
            PriceCache::clearProductPrice($data['product_id']);
        }
        
        return $result ? [RESULT_SUCCESS, '价格添加成功'] : [RESULT_ERROR, $this->modelPriceHistory->getError()];
    }
    
    /**
     * 价格编辑
     */
    public function priceEdit($data = [])
    {
        $validate_result = $this->validatePrice->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validatePrice->getError()];
        }
        
        // 获取原记录的product_id用于清除缓存
        $oldInfo = $this->modelPriceHistory->getInfo(['id' => $data['id']], 'product_id');
        
        $result = $this->modelPriceHistory->setInfo($data);
        
        if ($result) {
            action_log('编辑', '价格编辑，id：' . $data['id']);
            
            // 清除相关缓存
            if ($oldInfo && isset($oldInfo['product_id'])) {
                PriceCache::clearProductPrice($oldInfo['product_id']);
            }
            // 如果修改了product_id，也清除新product_id的缓存
            if (isset($data['product_id']) && $oldInfo['product_id'] != $data['product_id']) {
                PriceCache::clearProductPrice($data['product_id']);
            }
        }
        
        return $result ? [RESULT_SUCCESS, '价格编辑成功'] : [RESULT_ERROR, $this->modelPriceHistory->getError()];
    }
    
    /**
     * 价格删除
     */
    public function priceDel($data = [])
    {
        // 获取原记录的product_id用于清除缓存
        $oldInfo = $this->modelPriceHistory->getInfo(['id' => $data['id']], 'product_id');
        
        $where = ['id' => $data['id']];
        
        $result = $this->modelPriceHistory->deleteInfo($where);
        
        if ($result) {
            action_log('删除', '价格删除，id：' . $data['id']);
            
            // 清除相关缓存
            if ($oldInfo && isset($oldInfo['product_id'])) {
                PriceCache::clearProductPrice($oldInfo['product_id']);
            }
        }
        
        return $result ? [RESULT_SUCCESS, '价格删除成功'] : [RESULT_ERROR, $this->modelPriceHistory->getError()];
    }
    
    /**
     * 价格状态切换
     */
    public function priceStatus($data = [])
    {
        $where = ['id' => $data['id']];
        $update = ['status' => $data['status'], 'update_time' => time()];
        
        $result = $this->modelPriceHistory->updateInfo($where, $update);
        
        $result && action_log('状态', '价格状态切换，id：' . $data['id'] . '，status：' . $data['status']);
        
        return $result ? [RESULT_SUCCESS, '状态切换成功'] : [RESULT_ERROR, $this->modelPriceHistory->getError()];
    }
    
    /**
     * 价格导出
     */
    public function exportPriceList($where = [])
    {
        $list = $this->getPriceList($where, true, 'create_time desc', false);
        
        // 导出逻辑
        // TODO: 实现Excel导出功能
        
        return [RESULT_SUCCESS, '导出成功'];
    }
    
    /**
     * 获取价格统计
     */
    public function getPriceStats($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        $days = $data['days'] ?? 30;
        
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        try {
            // 先尝试从缓存获取
            $cachedStats = PriceCache::getCachedPriceStats($productId, $days);
            if ($cachedStats !== null) {
                return $cachedStats;
            }
            
            $startTime = time() - ($days * 86400);
            $where = [
                'product_id' => $productId,
                'create_time' => ['>=', $startTime]
            ];
            
            // 获取价格统计
            $maxPrice = $this->modelPriceHistory->getValue($where, 'MAX(price)') ?: 0;
            $minPrice = $this->modelPriceHistory->getValue($where, 'MIN(price)') ?: 0;
            $avgPrice = $this->modelPriceHistory->getValue($where, 'AVG(price)') ?: 0;
            $count = $this->modelPriceHistory->stat($where, 'count');
            
            $data = [
                'max_price' => $maxPrice,
                'min_price' => $minPrice,
                'avg_price' => round($avgPrice, 2),
                'count' => $count,
                'days' => $days
            ];
            
            // 缓存结果
            PriceCache::cachePriceStats($productId, $days, $data);
            
            return $data;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('获取价格统计失败：' . $e->getMessage());
            return [RESULT_ERROR, '获取价格统计失败'];
        }
    }
    
    /**
     * 获取价格详情
     */
    public function getPriceDetail($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        // 调用 getPriceInfo 方法获取商品价格信息
        return $this->getPriceInfo($data);
    }
    
    /**
     * 获取价格历史
     * 这里要注意一下，比如获取前10天数据，如果第10天前不是正好有数据，就要获取最接近的日期，比如11天或12天前的数据，因为11天或12天前之后到下一条数前，价格没有变化，这样前端不好自动填充，所以要获取一下以便前端填充
     */
    public function getPriceHistory($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        $days = $data['days'] ?? 30;
        $quickSelect = $data['quick_select'] ?? false; // 是否为快速选择模式
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        $where = ['product_id' => $productId];
        
        // 如果指定了天数，则按日期过滤
        if ($days > 0) {
            $startDate = date('Y-m-d', time() - ($days * 86400));
            $where['price_date'] = ['>=', $startDate];
        }
        
        // 设置分页参数
        $paginate = $quickSelect ? false : DB_LIST_ROWS;
        
        $list = $this->modelPriceHistory->getList($where, true, 'price_date desc, create_time desc', $paginate);
        
        // 确保返回数组格式
        // if (!is_array($list)) {
            //$list = [];
        // }
        
        if ($days > 0 && !$quickSelect) {
            $startDateForPrev = date('Y-m-d', time() - ($days * 86400));
            $prevRecord = $this->modelPriceHistory->getInfo([
                'product_id' => $productId,
                'price_date' => ['<', $startDateForPrev]
            ], true, 'price_date DESC');
            if (!empty($prevRecord)) {
                $list[] = $prevRecord;
            }
        }

        if ($quickSelect && !empty($list)) {
            $uniquePrices = [];
            $uniqueList = [];
            
            foreach ($list as $item) {
                $price = floatval($item['price']);
                if (!in_array($price, $uniquePrices)) {
                    $uniquePrices[] = $price;
                    $uniqueList[] = $item;
                    
                    // 限制返回5个不同的价格
                    if (count($uniqueList) >= 5) {
                        break;
                    }
                }
            }
            
            $list = $uniqueList;
        }
        
        return [RESULT_SUCCESS, '获取成功', $list];
    }

    /**
     * 获取价格变动记录（按时间倒序，用于后台管理查看）
     * 作者: 王勇程 (laughskydragon@qq.com)
     */
    public function getPriceChangeRecords($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        $where = ['product_id' => $productId];
        
        // 设置分页参数
        $paginate = DB_LIST_ROWS;
        
        // 按创建时间倒序获取所有变动记录，包括初始价格记录
        $list = $this->modelPriceHistory->getList($where, true, 'create_time desc', $paginate);
        
        // 计算变动前的价格（用于显示原价格）
        $records = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                $record = $item;
                // 计算原价格 = 新价格 - 变动金额
                $record['old_price'] = floatval($item['price']) - floatval($item['change_amount'] ?? 0);
                $records[] = $record;
            }
        }
        
        return [RESULT_SUCCESS, '获取成功', $records];
    }
    
    /**
     * 获取价格趋势数据
     * 作者: 王勇程 (laughskydragon@qq.com)
     * @param array $data 查询参数
     * @return array
     */
    public function getPriceTrend($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        $period = $data['period'] ?? '30d';
        if (!$productId) {
            return [RESULT_ERROR, '产品ID不能为空'];
        }
        
        // 提取天数
        if (preg_match('/^(\d+)d$/', $period, $matches)) {
            $days = intval($matches[1]);
        } else {
            $days = 30; // 默认30天
        }
        
        // 生成缓存键
        $cacheKey = "price_trend_{$productId}_{$period}";
        
        // 尝试从缓存获取数据
        $cachedData = \think\facade\Cache::get($cacheKey);
        if ($cachedData !== null && !empty($cachedData)) {
            return [RESULT_SUCCESS, '获取成功', $cachedData];
        }
        
        // 计算开始日期
        $startDate = date('Y-m-d', strtotime("-{$days} days"));
        
        // 查询条件
        $where = [
            'product_id' => $productId,
            'price_date' => ['>=', $startDate]
        ];
        
        $priceHistory = $this->modelPriceHistory->getList(
            $where,
            'price,price_date',
            'price_date ASC'
        );
        
        $trendData = [];
        if (!empty($priceHistory)) {
            foreach ($priceHistory as $item) {
                $trendData[] = [
                    'date' => $item['price_date'],
                    'price' => floatval($item['price'])
                ];
            }
        }
        
        $needPrev = empty($trendData) || ($trendData[0]['date'] > $startDate);
        if ($needPrev) {
            $prevRecord = $this->modelPriceHistory->getInfo([
                'product_id' => $productId,
                'price_date' => ['<', $startDate]
            ], 'price,price_date', 'price_date DESC');
            if (!empty($prevRecord)) {
                array_unshift($trendData, [
                    'date' => $prevRecord['price_date'],
                    'price' => floatval($prevRecord['price'])
                ]);
            }
        }
        
        $today = date('Y-m-d');
        $currentPrice = $this->modelProduct->getValue(['id' => $productId], 'market_price');
        if ($currentPrice === null) {
            $currentPrice = 0;
        }
        $lastIndex = count($trendData) - 1;
        if ($lastIndex >= 0) {
            $lastDate = $trendData[$lastIndex]['date'];
            if ($lastDate === $today) {
                $trendData[$lastIndex]['price'] = floatval($currentPrice ?: $trendData[$lastIndex]['price']);
            } else {
                $trendData[] = [
                    'date' => $today,
                    'price' => floatval($currentPrice ?: $trendData[$lastIndex]['price'])
                ];
            }
        } else {
            $trendData[] = [
                'date' => $today,
                'price' => floatval($currentPrice)
            ];
        }
        
        \think\facade\Cache::set($cacheKey, $trendData, 300);
        
        return [RESULT_SUCCESS, '获取成功', $trendData];
    }
    
    /**
     * 保存价格预警
     */
    public function savePriceAlert($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        $alertPrice = $data['alert_price'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        if (!$alertPrice) {
            return [RESULT_ERROR, '预警价格不能为空'];
        }
        
        $alertData = [
            'user_id' => $userId,
            'product_id' => $productId,
            'alert_price' => $alertPrice,
            'create_time' => time()
        ];
        
        $result = $this->modelPriceAlert->setInfo($alertData);
        
        return $result ? [RESULT_SUCCESS, '预警设置成功'] : [RESULT_ERROR, '预警设置失败'];
    }
    
    /**
     * 批量价格调整
     */
    public function batchPriceAdjust($data = [])
    {
        $productIds = $data['product_ids'] ?? [];
        $adjustType = $data['adjust_type'] ?? 'amount'; // amount: 金额调整, percent: 百分比调整
        $adjustValue = $data['adjust_value'] ?? 0;
        
        if (empty($productIds)) {
            return [RESULT_ERROR, '请选择要调整的商品'];
        }
        if (!$adjustValue) {
            return [RESULT_ERROR, '调整值不能为空'];
        }
        
        try {
            \think\facade\Db::transaction(function () use ($productIds, $adjustType, $adjustValue) {
                foreach ($productIds as $productId) {
                    // 获取当前价格
                    $currentPrice = $this->modelProduct->getValue(['id' => $productId], 'price');
                    
                    if ($adjustType == 'percent') {
                        $newPrice = $currentPrice * (1 + $adjustValue / 100);
                    } else {
                        $newPrice = $currentPrice + $adjustValue;
                    }
                    
                    // 更新商品价格
                    $this->modelProduct->updateInfo(['id' => $productId], ['price' => $newPrice]);
                    
                    // 记录价格历史，使用 addPriceHistory 方法处理唯一键冲突
                $historyResult = $this->modelPriceHistory->addPriceHistory(
                    $productId,
                    $newPrice,
                    $newPrice - $currentPrice,
                    (($newPrice - $currentPrice) / $currentPrice) * 100,
                    date('Y-m-d'),
                    MEMBER_ID
                );
                }
            });
            
            return [RESULT_SUCCESS, '批量调价成功'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('批量调价失败：' . $e->getMessage());
            return [RESULT_ERROR, '批量调价失败'];
        }
    }
    
    /**
     * 保存价格变动
     */
    public function savePriceChange($data = [])
    {
        try {
            $productId = $data['product_id'] ?? 0;
            $newPrice = floatval($data['price'] ?? 0);
            $priceDate = $data['price_date'] ?? date('Y-m-d');
            $reason = $data['reason'] ?? '';
            $remark = $data['remark'] ?? '';
            $onlyHistory = $data['only_history'] ?? false;
            
            if (!$productId || $newPrice <= 0) {
                return [RESULT_ERROR, '参数错误'];
            }
            
            // 获取当前价格
            $currentPrice = $this->modelProduct->getValue(['id' => $productId], 'market_price');
            
            if ($currentPrice === null) {
                \think\facade\Log::error('商品不存在', ['productId' => $productId]);
                return [RESULT_ERROR, '商品不存在'];
            }
            
            // 判断是否为当日价格（需要与当前价格比较）
            $isToday = $priceDate == date('Y-m-d');
            
            if ($isToday && $currentPrice == $newPrice) {
                \think\facade\Log::info('当日价格未发生变化', ['currentPrice' => $currentPrice, 'newPrice' => $newPrice]);
                return [RESULT_ERROR, '价格未发生变化'];
            }
            
            // 对于历史日期价格，检查是否与同日期已有价格相同
            if (!$isToday) {
                $existingPrice = $this->modelPriceHistory->getValue([
                    'product_id' => $productId,
                    'price_date' => $priceDate
                ], 'price');
                
                if ($existingPrice !== null && floatval($existingPrice) == $newPrice) {
                    \think\facade\Log::info('历史日期价格已存在相同价格', [
                        'productId' => $productId, 
                        'priceDate' => $priceDate,
                        'existingPrice' => $existingPrice,
                        'newPrice' => $newPrice
                    ]);
                    return [RESULT_ERROR, '该日期已存在相同价格'];
                }
            }
            
            \think\facade\Db::transaction(function () use ($productId, $newPrice, $currentPrice, $priceDate, $reason, $remark, $onlyHistory) {
                // 判断是否需要更新商品当前价格
                $isToday = $priceDate == date('Y-m-d');
                $shouldUpdateCurrentPrice = !$onlyHistory && $isToday;
                
                if ($shouldUpdateCurrentPrice) {
                    // 更新商品价格（仅当日且未勾选仅修改历史价格）
                    \think\facade\Log::info('开始更新商品价格', ['productId' => $productId, 'newPrice' => $newPrice]);
                    $updateResult = $this->modelProduct->updateInfo(['id' => $productId], ['market_price' => $newPrice]);
                    \think\facade\Log::info('商品价格更新结果', ['updateResult' => $updateResult]);
                } else {
                    \think\facade\Log::info('不更新商品当前价格', [
                        'onlyHistory' => $onlyHistory, 
                        'isToday' => $isToday,
                        'priceDate' => $priceDate
                    ]);
                }
                
                // 记录价格历史 - 在逻辑层处理业务逻辑
                $changeAmount = $newPrice - $currentPrice;
                $changePercent = $currentPrice > 0 ? (($newPrice - $currentPrice) / $currentPrice) * 100 : 0;
                
                $historyData = [
                    'product_id' => $productId,
                    'price' => $newPrice,
                    'change_amount' => $changeAmount,
                    'change_percent' => $changePercent,
                    'reason' => $reason,
                    'remark' => $remark,
                    'price_date' => $priceDate,
                    'member_id' => MEMBER_ID
                ];
                
                \think\facade\Log::info('开始处理价格历史记录', [
                    'historyData' => $historyData
                ]);
                
                // 检查是否已存在当日记录（处理唯一键冲突）
                $existingRecord = $this->modelPriceHistory->getInfo([
                    'product_id' => $productId,
                    'price_date' => $priceDate
                ]);
                
                \think\facade\Log::info('检查已存在记录结果', ['existingRecord' => $existingRecord]);
                
                if ($existingRecord) {
                    // 更新现有记录
                    \think\facade\Log::info('更新现有价格历史记录', ['existingId' => $existingRecord['id']]);
                    $historyResult = $this->modelPriceHistory->updateInfo([
                        'product_id' => $productId,
                        'price_date' => $priceDate
                    ], $historyData);
                    \think\facade\Log::info('更新价格历史记录结果', ['historyResult' => $historyResult]);
                } else {
                    // 创建新记录
                    \think\facade\Log::info('创建新价格历史记录');
                    $historyResult = $this->modelPriceHistory->setInfo($historyData);
                    \think\facade\Log::info('创建价格历史记录结果', ['historyResult' => $historyResult]);
                }
            });
            
            // 清除相关缓存
            PriceCache::clearProductPrice($productId);
            
            \think\facade\Log::info('价格变动保存成功');
            return [RESULT_SUCCESS, '价格变动保存成功'];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('价格变动保存失败异常', [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString()
            ]);
            return [RESULT_ERROR, '价格变动保存失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 导出价格历史
     */
    public function exportPriceHistory($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        $startTime = $data['start_time'] ?? '';
        $endTime = $data['end_time'] ?? '';
        
        $where = [];
        if ($productId) {
            $where['product_id'] = $productId;
        }
        if ($startTime) {
            $where['create_time'] = ['>=', strtotime($startTime)];
        }
        if ($endTime) {
            if (isset($where['create_time'])) {
                $where['create_time'] = ['between', [strtotime($startTime), strtotime($endTime)]];
            } else {
                $where['create_time'] = ['<=', strtotime($endTime)];
            }
        }
        
        $list = $this->modelPriceHistory->getList($where, true, 'create_time desc', false);
        
        // TODO: 实现Excel导出功能
        
        return [RESULT_SUCCESS, '导出成功', $list];
    }
    
    /**
     * 获取指定商品的昨日价格
     * @param int $productId 商品ID
     * @return float 昨日价格，如果不存在则返回0
     */
    public function getYesterdayPrice(int $productId): float
    {
        $yesterdayStart = strtotime(date('Y-m-d', strtotime('-1 day')));
        $yesterdayEnd = $yesterdayStart + 86400;
        $yesterdayPriceRecord = $this->modelPriceHistory->getInfo([
            'product_id' => $productId,
            'create_time' => ['between', [$yesterdayStart, $yesterdayEnd]]
        ]);
        return $yesterdayPriceRecord ? floatval($yesterdayPriceRecord['price']) : 0.00;
    }

    /**
     * 获取价格信息
     */
    public function getPriceInfo($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        // 获取商品信息
        $product = $this->modelProduct->getInfo(['id' => $productId]);
        if (!$product) {
            return [RESULT_ERROR, '商品不存在'];
        }
        
        // 获取最新价格记录
        $latestPrice = $this->modelPriceHistory->getInfo(
            ['product_id' => $productId],
            true,
            'create_time desc'
        );
        
        // 获取昨日价格
        $yesterdayStart = strtotime(date('Y-m-d', strtotime('-1 day')));
        $yesterdayEnd = $yesterdayStart + 86400;
        $yesterdayPrice = $this->modelPriceHistory->getInfo([
            'product_id' => $productId,
            'create_time' => ['between', [$yesterdayStart, $yesterdayEnd]]
        ]);
        
        $priceInfo = [
            'product_id' => $productId,
            'product_name' => $product['name'],
            'current_price' => $product['market_price'],
            'latest_price' => $latestPrice ? $latestPrice['price'] : $product['market_price'],
            'change_amount' => $product['change_amount'] ?? 0,
            'change_percent' => $product['change_rate'] ?? 0
        ];
        
        return [RESULT_SUCCESS, '获取成功', $priceInfo];
    }
    
    /**
     * 价格监控
     */
    public function priceMonitor($data = [])
    {
        $productId = $data['product_id'] ?? 0;
        $monitorType = $data['monitor_type'] ?? 'price_change'; // price_change: 价格变动, threshold: 阈值监控
        $threshold = $data['threshold'] ?? 0;
        $isEnabled = $data['is_enabled'] ?? 1;
        
        if (!$productId) {
            return [RESULT_ERROR, '商品ID不能为空'];
        }
        
        $monitorData = [
            'product_id' => $productId,
            'monitor_type' => $monitorType,
            'threshold' => $threshold,
            'is_enabled' => $isEnabled,
            'create_time' => time()
        ];
        
        $result = $this->modelPriceMonitor->setInfo($monitorData);
        
        return $result ? [RESULT_SUCCESS, '监控设置成功'] : [RESULT_ERROR, '监控设置失败'];
    }
    
    /**
     * 获取监控列表
     */
    public function getMonitorList($data = [])
    {
        $where = ['is_enabled' => 1];
        
        $list = $this->modelPriceMonitor->getList($where, true, 'create_time desc', false);
        
        return [RESULT_SUCCESS, '获取成功', $list];
    }
}
